package com.example.zbh.dsliao.ui.adapter;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.text.Html;
import android.text.Spannable;
import android.text.Spannable.Factory;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMChatRoom;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMGroup;
import com.easemob.chat.EMGroupManager;
import com.easemob.chat.EMMessage;
import com.easemob.chat.TextMessageBody;
import com.easemob.util.DateUtils;
import com.example.zbh.dsliao.R;
import com.example.zbh.dsliao.constant.Constant;
import com.example.zbh.dsliao.db.DatabaseHelper;
import com.example.zbh.dsliao.db.entity.UserContact;
import com.example.zbh.dsliao.utils.PreferenceHelper;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 会话界面适配器
 */
public class ConversartionListAdapter extends BaseAdapter{

    private ImageView avatar, msg_state;//用户头像, 消息提醒
    private TextView unread_msg_number, name, time, message;//消息数, 用户姓名, 最后一条时间, 消息内容
    private RelativeLayout list_itease_layout;//行布局

    private List<EMConversation> emConversations;
    private List<EMConversation> copyEmConversations;
    private List<UserContact> userContacts;//第三方管理的头像昵称实体类

    private static final Factory spannableFactory = Spannable.Factory.getInstance();
    private static final Map<Pattern, Object> emoticons = new HashMap<Pattern, Object>();
    private Context context;

    private boolean notifyByFilter;
    private ConversationFilter conversationFilter;
    private AssetManager manager;
    private Typeface typeface;

    private  String nowname;


    public ConversartionListAdapter(Context context) {
        this.context = context;
        manager = context.getAssets();
    }

    public void addData(List<EMConversation> emConversations){
        this.emConversations = emConversations;
        Log.i("nangeyao", emConversations.size() + "  "+Thread.currentThread().getId());
        copyEmConversations = new ArrayList<EMConversation>();
        copyEmConversations.addAll(emConversations);
        notifyDataSetChanged();
    }

    public boolean isLength(){
        return emConversations != null && emConversations.size() > 0;
    }


    @Override
    public int getCount() {
        return isLength() ? emConversations.size() : 0;
    }

    @Override
    public EMConversation getItem(int position) {
        if (position < emConversations.size()){
            return emConversations.get(position);
        }
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        if (convertView == null){
            LayoutInflater inflater = LayoutInflater.from(parent.getContext());
            convertView = inflater.inflate(R.layout.fragment_conversationlist_gut, null);
        }

        avatar = (ImageView) convertView.findViewById(R.id.avatar);
        msg_state = (ImageView) convertView.findViewById(R.id.msg_state);
        unread_msg_number = (TextView) convertView.findViewById(R.id.unread_msg_number);
        name = (TextView) convertView.findViewById(R.id.name);
        time = (TextView) convertView.findViewById(R.id.time);
        message = (TextView) convertView.findViewById(R.id.message);
        list_itease_layout = (RelativeLayout) convertView.findViewById(R.id.list_itease_layout);
        list_itease_layout.setBackgroundResource(R.drawable.dl_mm_listitem);
        message.setTypeface(Typeface.DEFAULT);
        message.setTextColor(Color.GRAY);
        message.setTextSize(14);



        if (isLength()){
            //获取此用户/群组的会话
            EMConversation conversation = getItem(position);
            //获取用户username或群组的groupid
            String username = conversation.getUserName();

            if (conversation.getType() == EMConversation.EMConversationType.GroupChat){
                avatar.setImageResource(R.drawable.dl_group_icon);
                EMGroup group = EMGroupManager.getInstance().getGroup(username);
                name.setText(group != null ? group.getGroupName() : username);
            }else if (conversation.getType() == EMConversation.EMConversationType.ChatRoom){
                avatar.setImageResource(R.drawable.dl_groups_icon);
                EMChatRoom room = EMChatManager.getInstance().getChatRoom(username);
                name.setText(room != null && !TextUtils.isEmpty(room.getName()) ? room.getName() : username);
            }else {
                EMMessage lastEmMessage = conversation.getLastMessage();
                if (lastEmMessage != null){
                    UserContact userContact = DatabaseHelper.getInstance().queryContactPeopleByName(username);
                    if (userContact != null){
                        if (userContact.getNickname() != null){
                            nowname = userContact.getNickname();
                            name.setText(nowname);
                        }else {
                            name.setText(lastEmMessage.getUserName());
                        }
                        if (userContact.getAvatar() != null){
                            String nowavatar = userContact.getAvatar();
                            setUserAvatar(context, nowavatar, avatar);
                        }else {
                            avatar.setImageResource(R.drawable.dl_default_avatar);
                        }
                    }else {
                        name.setText(lastEmMessage.getUserName());
                        avatar.setImageResource(R.drawable.dl_default_avatar);
                    }
                }
            }

            //用户与此用户的消息未读数
            if (conversation.getUnreadMsgCount() > 0){
                unread_msg_number.setText(String.valueOf(conversation.getUnreadMsgCount()));
                Log.d("geanwenfe", "conversation.getUnreadMsgCount():" + conversation.getUnreadMsgCount());
                unread_msg_number.setVisibility(View.VISIBLE);
            }else {
                unread_msg_number.setVisibility(View.INVISIBLE);
            }

            //把最后一条消息作为item的messag内容
            if (conversation.getMsgCount() != 0){
                EMMessage lastEmMessage = conversation.getLastMessage();
                if (lastEmMessage.getType() == EMMessage.Type.IMAGE){
                    message.setText("[图片]");
                }else if (lastEmMessage.getType()== EMMessage.Type.TXT){
                    String text =((TextMessageBody)lastEmMessage.getBody()).getMessage();
                    CharSequence cs = Html.fromHtml(text, imageGetter, null);
                    setHolderText(message);
                    message.setText(cs);
                }else if (lastEmMessage.getType() == EMMessage.Type.FILE){
                    message.setText("[文件]");
                }else if (lastEmMessage.getType() == EMMessage.Type.VIDEO){
                    message.setText("[视频]");
                }else if(lastEmMessage.getType() == EMMessage.Type.VOICE){
                    message.setText("[语音]");
                }


                list_itease_layout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (onItemLongClickListenerConversartion != null){
                            onItemLongClickListenerConversartion.onlongclick(v, 1, position);
                        }
                    }
                });
                list_itease_layout.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        if (onItemLongClickListenerConversartion != null) {
                            onItemLongClickListenerConversartion.onlongclick(v, 2, position);
                        }
                        return true;
                    }
                });

                //设置时间(最后一条的时间)
                time.setText(DateUtils.getTimestampString(new Date(lastEmMessage.getMsgTime())));
            }
        }
        return convertView;
    }
    //设置聊天字体属性
    private void setHolderText(TextView holderText) {
        String textType = PreferenceHelper.getInstance().getCurrentTextType();
        String textColor = PreferenceHelper.getInstance().getCurrentuserTextColor();
        String textSize = PreferenceHelper.getInstance().getCurrentTextSize();
        if (textType != null){
            switch (textType){
                case Constant.TYPE_01:
                    typeface = Typeface.createFromAsset(manager, "xindixiaowanzi.ttf");
                    holderText.setTypeface(typeface);
                    break;
                case Constant.TYPE_02:
                    typeface = Typeface.createFromAsset(manager,"xindiwenguimingti.ttf");
                    holderText.setTypeface(typeface);
                    break;
                case Constant.TYPE_03:
                    typeface = Typeface.DEFAULT;
                    holderText.setTypeface(typeface);
                    break;
            }
        }
        if (textColor != null){
            switch (textColor){
                case Constant.COLOR_01:
                    int colorb = Constant.COLOR_BLACK;
                    holderText.setTextColor(colorb);
                    break;
                case Constant.COLOR_02:
                    int colorw = Constant.COLOR_WHITE;
                    holderText.setTextColor(colorw);
                    break;
                case Constant.COLOR_03:
                    int colorr = Constant.COLOR_GREEN;
                    holderText.setTextColor(colorr);
                    break;
                case Constant.COLOR_04:
                    int colorg = Constant.COLOR_RED;
                    holderText.setTextColor(colorg);
                    break;
            }
        }
        if (textSize != null){
            switch (textSize){
                case Constant.SIZE_01:
                    float l = Constant.SIZE_LARGE;
                    holderText.setTextSize(l);
                    break;
                case Constant.SIZE_02:
                    float m = Constant.SIZE_MIDDLE;
                    holderText.setTextSize(m);
                    break;
                case Constant.SIZE_03:
                    float s = Constant.SIZE_SMALL;
                    holderText.setTextSize(s);
                    break;
            }
        }

    }

    private void setUserAvatar(Context context, String avater, ImageView userImg) {
        if (avater != null){
            Glide.with(context).load(avater).into(userImg);
            Log.d("wonima", "wonima" + ">>>>>");
        }
    }


    public boolean addSmiles(Context context, Spannable spannable){
        boolean hasChange = false;
        for (Map.Entry<Pattern, Object> entry : emoticons.entrySet()){
            Matcher matcher = entry.getKey().matcher(spannable);
            while (matcher.find()){
                boolean set = true;
                for (ImageSpan span : spannable.getSpans(matcher.start(), matcher.end(), ImageSpan.class))
                    if (spannable.getSpanStart(span) >= matcher.start() && spannable.getSpanEnd(span) <= matcher.end())
                        spannable.removeSpan(span);
                    else {
                        set = false;
                        break;
                    }
                if (set){
                    hasChange = true;
                    Object value = entry.getValue();
                    if(value instanceof String && !((String) value).startsWith("http")){
                        File file = new File((String) value);
                        if(!file.exists() || file.isDirectory()){
                            return false;
                        }
                        spannable.setSpan(new ImageSpan(context, Uri.fromFile(file)),
                                matcher.start(), matcher.end(),
                                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    }else{
                        spannable.setSpan(new ImageSpan(context, (Integer)value),
                                matcher.start(), matcher.end(),
                                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    }
                }
            }
        }

        return hasChange;
    }


    public Spannable getSmiledText(Context context, CharSequence text) {
        Spannable spannable = spannableFactory.newSpannable(text);
        addSmiles(context, spannable);
        return spannable;
    }


    private OnItemLongClickListenerConversartion onItemLongClickListenerConversartion;
    public void setOnItemLongClickListenerConversartion(OnItemLongClickListenerConversartion onItemLongClickListenerConversartion){
           this.onItemLongClickListenerConversartion = onItemLongClickListenerConversartion;
    }
    /**
     * listView行布局点击事件 接口
     * **/
    public interface OnItemLongClickListenerConversartion{
        void onlongclick(View v, int code, int position);
    }

    private Html.ImageGetter imageGetter = new Html.ImageGetter() {
        @Override
        public Drawable getDrawable(String source) {
            int id = Integer.parseInt(source);
            Drawable drawable = context.getResources().getDrawable(id);
            drawable.setBounds(0,0,drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight());
            return drawable;
        }
    };



//    /**
//     * 刷新
//     * **/
//    @Override
//    public void notifyDataSetChanged() {
//        super.notifyDataSetChanged();
//        if (!notifyByFilter){
//            copyEmConversations.clear();
//            copyEmConversations.addAll(emConversations);
//            notifyByFilter = false;
//        }
//    }



    /**
     * 向过滤器发送
     * **/
    public Filter getFilter() {
        if (conversationFilter == null) {
            conversationFilter = new ConversationFilter(emConversations);
        }
        return conversationFilter;
    }

    /**
     * 会话界面的搜索过滤器
     * (单独搜群组有问题)
     * **/
    private class ConversationFilter extends Filter{
        List<EMConversation> Conversations;

        public ConversationFilter(List<EMConversation> emConversations){
            this.Conversations = emConversations;
        }

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults results = new FilterResults();

            if (Conversations == null){
                Conversations = new ArrayList<EMConversation>();
            }
            if (constraint == null || constraint.length() == 0){
                results.values = copyEmConversations;
                results.count = copyEmConversations.size();
            }else {
                String constraintString = constraint.toString();
                final int cout = Conversations.size();
                final ArrayList<EMConversation> newValues = new ArrayList<EMConversation>();

                for (int i = 0; i < cout; i++){
                    final EMConversation values = Conversations.get(i);
                    String username = values.getUserName();

                    EMGroup group = EMGroupManager.getInstance().getGroup(username);
                    if (group != null){
                        username = group.getGroupName();
                    }else {
                        EMConversation conversation = Conversations.get(i);
                        String user = conversation.getUserName();
                        if (user.equals(username)) {
                            user = username;
                        }
                    }
                    if (username.startsWith(constraintString)){
                        newValues.add(values);
                    }else {
                        final String[] words = username.split(" ");
                        final int wordCount = words.length;
                        for (int k = 0; k < wordCount; k++){
                            if (words[k].startsWith(constraintString)){
                                newValues.add(values);
                                break;
                            }
                        }
                    }

                }
                results.values = newValues;
                results.count = newValues.size();
            }
            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            emConversations.clear();
            emConversations.addAll((List<EMConversation>)results.values);
            if (results.count > 0){
                notifyByFilter = true;
                notifyDataSetChanged();
            }else {
                notifyDataSetChanged();
            }

        }
    }





}
